package com.codemart.lanze.core.freemarker;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codemart.lanze.core.freemarker.utils.Freemarker;
import com.codemart.lanze.modules.cms.entity.Channel;
import com.codemart.lanze.modules.cms.service.IChannelService;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.WrappingTemplateModel;

/**
 * 栏目列表指令
 *
 * @author lanze
 */
@Repository
public class DirectiveChannelList implements TemplateDirectiveModel {

	@Autowired
	private IChannelService channelService;

	/**
	 * @param pId:
	 *            上级栏目ID size: 数量 isNav: 是否是导航 fields: 排序字段 sort: 排序规则 asc/desc
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
	@Override
	public void execute(Environment env, Map map, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {

		Integer pId = Freemarker.getInteger(map, "pId");
		Integer isNav = Freemarker.getInteger(map, "isNav");
		String fields = Freemarker.getString(map, "fields");
		String sort = Freemarker.getString(map, "sort");
		QueryWrapper<Channel> ew = new QueryWrapper<>();
		/** 显示记录条数 */
		Integer size = Freemarker.getInteger(map, "size");
		size = size == null ? 10 : size;

		if (pId != null) {
			ew.eq("p_id", pId);
		} else {
			ew.isNull("p_id");
		}
		if (isNav != null) {
			ew.eq("is_nav", isNav);
		} else {
			ew.isNull("is_nav");
		}

		ew.last("limit " + size);

		if (StringUtils.isNotBlank(fields)) {
			String[] f = StringUtils.split(fields, ",");
			String[] s = StringUtils.split(sort, ",");
			for (int i = 0; i < f.length; i++) {
				if ("asc".equals(s[i])) {
					ew.orderByAsc(f[i]);
				} else {
					ew.orderByDesc(f[i]);
				}
			}
		}

		List<Channel> list = channelService.list(ew);
		loopVars[0] = WrappingTemplateModel.getDefaultObjectWrapper().wrap(list);
		body.render(env.getOut());
	}

}
